package com.example.sherlockzhong.plush_v2;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.Models.DataModel;
import com.example.sherlockzhong.plush_v2.Models.UserModel;
import com.umeng.analytics.MobclickAgent;

/**
 * Created by DosonLeungs on 2014/9/20.
 */
public class LoginActivity extends Activity {

    Handler mHandler;
    private LoginActivity self = this;
    private boolean keyBackPressed = false;
    private Handler keyBackHandler = new Handler();
    private String userName;
    private String passWord;
    private EditText etName, etPass;
    private Button bnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);
        initWidgets();
        initRecord();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!keyBackPressed) {
                keyBackPressed = true;
                Toast.makeText(LoginActivity.this, "再按一次后退键将会退出", Toast.LENGTH_SHORT).show();
                keyBackHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        keyBackPressed = false;
                    }
                }, 3000);
            } else {
                self.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化所有组件和Handler
     */
    private void initWidgets() {
        etName = (EditText) findViewById(R.id.login_username);
        etPass = (EditText) findViewById(R.id.login_password);
        bnLogin = (Button) findViewById(R.id.login_button);
        bnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressLogin();
            }
        });
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x200) {
                    startMainActivity();
                } else if (msg.what == 0x500) {
                    bnLogin.setText("登录");
                    Toast.makeText(LoginActivity.this, "数据同步失败，请在设置界面中重新同步", Toast.LENGTH_LONG).show();
                    startMainActivity();
                } else if (msg.what == 0x401) {
                    bnLogin.setText("登录");
                    Toast.makeText(LoginActivity.this, "学号或者密码错误", Toast.LENGTH_LONG).show();
                } else if (msg.what == 0x404) {
                    bnLogin.setText("登录");
                    Toast.makeText(LoginActivity.this, "网络超时", Toast.LENGTH_LONG).show();
                }
            }
        };
    }

    private void initRecord() {
        userName = null;
        SharedPreferences sp = getSharedPreferences("user", Context.MODE_PRIVATE);
        if (!sp.getString("studentID", "").equalsIgnoreCase("") && !sp.getString("token", "").equalsIgnoreCase("")) {
            userName = sp.getString("studentID", "");
            startMainActivity();
        } else if (!sp.getString("studentID", "").equalsIgnoreCase("")) {
            etName.setText(sp.getString("studentID", ""));
            etPass.requestFocus();
        }
    }

    private boolean validate() {
        userName = etName.getText().toString().trim();
        if (userName.equals("")) {
            Toast.makeText(this, "请输入学号", Toast.LENGTH_LONG).show();
            etName.setFocusable(true);
            etName.requestFocus();
            return false;
        }
        passWord = etPass.getText().toString().trim();
        if (passWord.equals("")) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_LONG).show();
            etPass.setFocusable(true);
            etPass.requestFocus();
            return false;
        }
        return true;
    }

    private void pressLogin() {
        if (validate()) {
            bnLogin.setText("登录中...");
            DataModel.removeUserData(self);
            new Thread() {
                boolean validate;
                Message msg = new Message();

                @Override
                public void run() {
                    String result = UserModel.login(userName, passWord, self);
                    if (result == null) {
                        msg.what = 0x404;
                    } else if (result.contains("login failed")) {
                        msg.what = 0x401;
                    } else if (!DataModel.sync()) {
                        msg.what = 0x500;
                    } else {
                        msg.what = 0x200;
                    }
                    mHandler.sendMessage(msg);
                }
            }.start();
        } else
            return;
    }

    private void startMainActivity() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        LoginActivity.this.finish();
    }
}
